package com.example.gateway.filter;

import com.example.common.exception.UnauthorizedException;
import com.example.common.utils.JwtUtils;
import com.example.common.utils.RedisUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisUtils redisUtils;

    // 白名单接口（无需认证）
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/api/auth/login",
            "/doc.html",
            "/webjars/**",
            "/v2/**",
            "/swagger-ui.html"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 1. 白名单接口直接放行
        if (WHITE_LIST.stream().anyMatch(path::startsWith)) {
            return chain.filter(exchange);
        }

        // 2. 从请求头获取令牌
        String token = request.getHeaders().getFirst("Authorization");
        if (token == null || token.isEmpty()) {
            throw new UnauthorizedException("令牌不存在");
        }

        // 3. 验证令牌有效性
        if (!jwtUtils.validateToken(token)) {
            throw new UnauthorizedException("令牌无效或已过期");
        }

        // 4. 验证令牌是否在Redis中（未被登出）
        if (!redisUtils.hasToken(token)) {
            throw new UnauthorizedException("令牌已失效，请重新登录");
        }

        // 5. 令牌有效，继续请求
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100; // 优先级高于其他过滤器
    }
}
